package hhm.zimu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileUtil {

	public void writeToTxt(String str, String path) {
		File file = new File(path); // 找到File类的实例

		try {
			// 创建文件
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(path);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			osw.write(str);
			osw.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getFromTxt2(String path) {
		String result = "";
		File file = new File(path);
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(path);
		try {
			String encoding = "utf-8";

			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file), encoding);// 考虑到编码格式
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			String kongge = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {

				result = result + lineTxt + "\n";

			}
			read.close();

			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;

	}

	public String getFromTxt(String path) {
		String result = "";
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(path);
		try {
			String encoding = "utf-8";

			InputStreamReader read = new InputStreamReader(in, encoding);// 考虑到编码格式
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				// System.out.println(lineTxt);
			}
			read.close();
			return lineTxt;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;

	}

	public boolean copy(String fileFrom, String fileTo) {
		try {
			FileInputStream in = new java.io.FileInputStream(fileFrom);
			FileOutputStream out = new FileOutputStream(fileTo);
			byte[] bt = new byte[1024];
			int count;
			while ((count = in.read(bt)) > 0) {
				out.write(bt, 0, count);
			}
			in.close();
			out.close();
			return true;
		} catch (IOException ex) {
			return false;
		}
	}

}
